using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Infrastructure;
using SupplierCustomerManagement.Read.API.Applications.Commands.breeding;
using SupplierCustomerManagement.Read.API.Dtos.Breeding;

namespace SupplierCustomerManagement.Read.API.Applications.CommandHandlters.breeding
{
    public class GetBreedingRateQueryHandler : IRequestHandler<GetBreedingRateQuery, BreedingRateDto>
    {
        private readonly SupplierDbContext _db;
        private readonly ILogger<GetBreedingRateQueryHandler> _logger;

        public GetBreedingRateQueryHandler(SupplierDbContext db, ILogger<GetBreedingRateQueryHandler> logger)
        {
            _db = db;
            _logger = logger;
        }

        public async Task<BreedingRateDto> Handle(GetBreedingRateQuery request, CancellationToken cancellationToken)
        {
            var months = new[] { "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" };
            var breedingCount = new int[12];
            var lambingCount = new int[12];
            var lambingRate = new decimal[12];

            if (!int.TryParse(request.Year, out var year))
            {
                year = DateTime.UtcNow.Year;
            }

            // 配种：按月去重种母数
            var breedingByMonth = await _db.BreedingRecords
                .AsNoTracking()
                .Where(r => r.BreedingDate.Year == year)
                .Select(r => new { r.EweId, Month = r.BreedingDate.Month })
                .Distinct()
                .GroupBy(x => x.Month)
                .Select(g => new { Month = g.Key, Count = g.Count() })
                .ToListAsync(cancellationToken);

            foreach (var item in breedingByMonth)
            {
                if (item.Month >= 1 && item.Month <= 12)
                    breedingCount[item.Month - 1] = item.Count;
            }

            // 分娩：按月去重种母数
            var lambingByMonth = await _db.LambingRecords
                .AsNoTracking()
                .Where(r => r.LambingDate.Year == year)
                .Select(r => new { r.EweId, Month = r.LambingDate.Month })
                .Distinct()
                .GroupBy(x => x.Month)
                .Select(g => new { Month = g.Key, Count = g.Count() })
                .ToListAsync(cancellationToken);

            foreach (var item in lambingByMonth)
            {
                if (item.Month >= 1 && item.Month <= 12)
                    lambingCount[item.Month - 1] = item.Count;
            }

            for (int i = 0; i < 12; i++)
            {
                lambingRate[i] = breedingCount[i] == 0 ? 0 : Math.Round((decimal)lambingCount[i] / breedingCount[i], 4);
            }

            return new BreedingRateDto
            {
                months = months,
                breedingCount = breedingCount,
                lambingCount = lambingCount,
                lambingRate = lambingRate
            };
        }
    }
}
